<template>
  <div>
    <div v-show="loading">加载中...</div>
    <div v-show="!loading && !cartStore.cartList.length">购物车为空！</div>

    <div v-show="!loading">
      <div v-for="(item, index) in cartStore.cartList" :key="index">
        id：{{ item.goodsId }} 名称：{{ item.goodsName }} 数量：{{
          item.number
        }}
        操作：
        <button @click="cartStore.addCart(item)">+</button>
        &nbsp;&nbsp;
        <button @click="cartStore.reduceCart(item)">-</button>
        &nbsp;&nbsp;
        <button @click="cartStore.removeCart(item)">X</button>
      </div>
    </div>

    <div>
      <br />
      <input
        v-model="goodsForm.goodsName"
        type="text"
        placeholder="请输入名称"
      />
      <br />
      <input
        v-model="goodsForm.number"
        type="number"
        placeholder="请输入数量"
      />
      <br />
      <button @click="handleAddGoods">添加</button>
    </div>
  </div>
</template>

<script lang="ts">
export default {
  name: "Pinia",
};
</script>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";

// #region 购物车相关
import { useCartStore } from "@/pinia-store/cart";
const cartStore = useCartStore();

import { Goods } from "@/entity/Goods";

const loading = ref(false);

function getCartList() {
  loading.value = true;
  cartStore
    .getCartList({
      page: 1,
      limit: 10,
    })
    .finally(() => {
      loading.value = false;
    });
}

onMounted(getCartList);

// 表单
const goodsForm = reactive<Goods>({
  goodsId: 0,
  goodsName: "",
  number: 1,
});

// 重新设置表单
function resetGoodsForm() {
  goodsForm.goodsId = 0;
  goodsForm.goodsName = "";
  goodsForm.number = 1;
}

// 添加
function handleAddGoods() {
  if (!goodsForm.goodsName) {
    alert("请输入商品名称");
  } else if (goodsForm.number < 1) {
    alert("请输入正确的数量");
  } else {
    // 如果没有 id，根据列表生成
    if (!goodsForm.goodsId) {
      goodsForm.goodsId = cartStore.cartList.length + 1;
    }
    cartStore.addCart(goodsForm);
  }
  // 重新设置表单
  resetGoodsForm();
}

// #endregion
</script>
